import CryptoJS from 'crypto-js';


// 128位的密钥与IV，与后端约定好
const crypt_key = 'OS7kWn9kGLmr7wxD';
const crypt_iv = 'AgBJQGRaHehjSgjT';
 
// 加密
export function encryptionAES(data: any) {
    // 将key解析为字节
    const aes_key = CryptoJS.enc.Utf8.parse(crypt_key);
    // 将iv解析为字节
    const new_iv = CryptoJS.enc.Utf8.parse(crypt_iv);
    // AES加密 CBC模式 ZeroPadding
    const encrypted = CryptoJS.AES.encrypt(data, aes_key, { 
        iv: new_iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
    });
    // 返回字符串
    return encrypted.toString();
}

//解密
export function decryptionAES(data: any) {
    const aes_key = CryptoJS.enc.Utf8.parse(crypt_key);
    const aes_iv = CryptoJS.enc.Utf8.parse(crypt_iv);
     // 将数据编码成Base64格式
     const baseResult=CryptoJS.enc.Base64.parse(data);  
     const ciphertext=CryptoJS.enc.Base64.stringify(baseResult);
    // AES解密 CBC模式 ZeroPadding
    const decryptResult = CryptoJS.AES.decrypt(ciphertext, aes_key, {    
        iv: aes_iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
    });
    // 返回字符串
    const resData = decryptResult.toString(CryptoJS.enc.Utf8).toString();
    return resData;
}


